//
//  ThirdViewController.m
//  Demo
//
//  Created by 龚碧容 on 2017/9/15.
//  Copyright © 2017年 hwd. All rights reserved.
//

#import "ThirdViewController.h"
#import "QLMDeviceListTabCell.h"
#import "QLMBXOrderListVC.h"
#import "QLMDeviceListModel.h"

@interface ThirdViewController ()<UITableViewDelegate,UITableViewDataSource>{
   
    QLMDeviceListModel *deviceListModel;
    QLMCustomTipView *tipView;

    NSInteger currentPage;
}

@property (nonatomic, strong) UITableView *devicetableview;
@property (nonatomic, strong) UIImageView *navBarHairlineImageView;

@end

@implementation ThirdViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.navigationItem.title=@"设备订单";
    self.view.backgroundColor = UIColorFromRGB(0xf5f5f5);
    
    currentPage=1;
    deviceListModel=[[QLMDeviceListModel alloc] init];
    deviceListModel.list=[NSMutableArray array];
    
    _navBarHairlineImageView = [ClientTool findHairlineImageViewUnder:self.navigationController.navigationBar];
    CGRect rect=CGRectMake(0, 0, kScreen_width, kScreen_height-QLM_StatusBarAndNavigationBarHeight-49-1-IOS11_OR_LATER_SPACE(34));
    _devicetableview=[[UITableView alloc] initWithFrame:rect style:UITableViewStylePlain];
    _devicetableview.backgroundColor=[UIColor clearColor];
    _devicetableview.delegate=self;
    _devicetableview.dataSource=self;
    _devicetableview.separatorStyle=UITableViewCellSeparatorStyleSingleLine;
    _devicetableview.showsVerticalScrollIndicator=NO;
    _devicetableview.showsHorizontalScrollIndicator=NO;
    _devicetableview.tableFooterView=[UIView new];
    [self.view addSubview:_devicetableview];
    
    //上拉刷新
    _devicetableview.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(requestData)];
    _devicetableview.mj_footer.automaticallyHidden = YES;
    
    tipView=[QLMCustomTipView sharedInstance];
    tipView.hidden = YES;
    [_devicetableview addSubview:tipView];
}

- (void)presentaLoginVC{
    QLMLoginViewController *loginController = [QLMLoginViewController new];
    loginController.resultBlock=^(BOOL success){};
    QLMCustomNavCtr *nav=[[QLMCustomNavCtr alloc] initWithRootViewController:loginController];
    [self.navigationController presentViewController:nav animated:YES completion:nil];
}

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    _navBarHairlineImageView.hidden=YES;
    
    if ([[UserManager sharedManager] isUserLogin]) {
        [self requestData];
    }else{
        [self presentaLoginVC];
    }
    
    [MobClick beginLogPageView:self.title];
}

- (void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    _navBarHairlineImageView.hidden=NO;
    
    [deviceListModel.list removeAllObjects];
    currentPage=1;
    
    [MobClick endLogPageView:self.title];
}

- (void)requestData{
    NSString *token=[[NSUserDefaults standardUserDefaults] objectForKey:kLoginToken];
    NSDictionary *tokenDic=[NSDictionary dictionaryWithObjectsAndKeys:token,@"token", nil];
    if ([token length]==0) {
        [_devicetableview reloadData];
        return;
    }

    NSMutableDictionary *paramerDic=[NSMutableDictionary dictionary];
    [paramerDic setObject:[NSString stringWithFormat:@"%ld",currentPage] forKey:@"page"];
    [paramerDic setObject:@"10" forKey:@"rows"];
    
    [self.view makeToastActivity:CSToastPositionCenter];
    [ClientTool postUrlPath:@"/test/equipmentManager" withParamers:paramerDic andBody:tokenDic
                    success:^(id responseObject){
                        [self.view hideToastActivity];
                        
                        [_devicetableview.mj_footer endRefreshing];
                        
                        NSInteger code = [[responseObject objectForKey:@"flag"] integerValue];
                        if (code == 1) {
                            [deviceListModel.list addObjectsFromArray:responseObject[@"list"]];
                            
                            if (deviceListModel.list.count==0) {
                                tipView.hidden = NO;
                            }else{
                                if ([responseObject[@"list"] count]<10) {
                                    _devicetableview.mj_footer.state = MJRefreshStateNoMoreData;
                                }
                                tipView.hidden = YES;
                                currentPage++;
                            }
                            [_devicetableview reloadData];
                            
                        }else{
                            ETToast(responseObject[@"msg"]);
                        }
                        
                    }failure:^(NSError *error){
                        [self.view hideToastActivity];
                        ETToast(@"服务器连接失败");
                        [_devicetableview.mj_footer endRefreshing];
                    }
     ];
}

#pragma mark - UIButton Action
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - UITableView datasource
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 5;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    UIView *headerView=[[UIView alloc] init];
    headerView.backgroundColor=[UIColor clearColor];
    return headerView;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return 1;
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return deviceListModel.list.count;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 120;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    QLMDeviceListTabCell *cell=[QLMDeviceListTabCell cellWithTableView:tableView];
    cell.selectionStyle=UITableViewCellSelectionStyleNone;
    
    if (deviceListModel.list.count!=0) {
        QLMDeviceInfoModel *deviceInfoModel=[[QLMDeviceInfoModel alloc] initWithDictionary:deviceListModel.list[indexPath.section] error:nil];

        cell.devicenameLabel.text=[NSString stringWithFormat:@"设备：%@%@",deviceInfoModel.brandName,deviceInfoModel.modelName];
        
        cell.carNumLabel.hidden=YES;
        cell.carNumLabel.text=[NSString stringWithFormat:@"机号：%@",deviceInfoModel.serialNo];
        
        NSString *otherName=nil;
        if (deviceInfoModel.alias.length==0) {
            otherName=@"无";
        }else{
            otherName=deviceInfoModel.alias;
        }
        cell.othernameLabel.text=[NSString stringWithFormat:@"别名：%@",otherName];
        
        if (deviceInfoModel.serialNo.length==0) {
            cell.seriNoLab.text=@"机号：无";
        }else{
            cell.seriNoLab.text=[NSString stringWithFormat:@"机号：%@",deviceInfoModel.serialNo];
        }
        
        NSString *telStr=[NSString stringWithFormat:@"未完成订单：%ld",[deviceInfoModel.unfinishedOrder integerValue]];
        NSMutableAttributedString *aString=[[NSMutableAttributedString alloc] initWithString:telStr];
        [aString addAttribute:NSForegroundColorAttributeName value:UIColorFromRGB(0xf3ca20) range:NSMakeRange(6, telStr.length-6)];
        
        cell.statusNumLabel.attributedText=aString;
    }
    
    return cell;
}

#pragma mark - UITableView delegate
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    QLMDeviceInfoModel *deviceInfoModel=[[QLMDeviceInfoModel alloc] initWithDictionary:deviceListModel.list[indexPath.section] error:nil];
    QLMBXOrderListVC *bxOrderVC=[QLMBXOrderListVC new];
    bxOrderVC.equipmentIdStr=deviceInfoModel.equipmentId;
    self.hidesBottomBarWhenPushed=YES;
    [self.navigationController pushViewController:bxOrderVC animated:YES];
    self.hidesBottomBarWhenPushed=NO;
}

@end
